import { Button, message, Modal, Tree, Badge, Tag, Divider } from "antd";
import { useEffect, useState, useMemo } from "react";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import "./permissionSelect.css";

/**
 * 权限选择控件
 *
 * 外部需要使用此控件时, 必须传入以下参数:
 *  - visible: 控件是否可见
 *  - setVisible: 控件显示状态设置函数
 *  - permissions: 已选权限列表（初始可传入code数组或对象数组）
 *  - setPermissions: 已选权限列表设置函数（返回完整权限对象数组）
 *
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
const PermissionSelect = (props) => {
    const {
        visible,
        setVisible,
        permissions,
        setPermissions
    } = props;

    const [messageApi, setContextHolder] = message.useMessage();
    const [selectedKeys, setSelectedKeys] = useState([]); // 左侧树选中的节点code集合
    const [selectedPermissions, setSelectedPermissions] = useState([]); // 右侧已选叶子节点（完整对象）
    const [permissionTree, setPermissionTree] = useState({});
    const [permissionMap, setPermissionMap] = useState(new Map()); // key: permissionCode, value: 完整权限对象
    const [totalPermissionCount, setTotalPermissionCount] = useState(0);
    const [allLeafPermissions, setAllLeafPermissions] = useState([]); // 所有叶子节点（完整对象）
    const [nodeRelations, setNodeRelations] = useState({
        allAncestorsMap: new Map(), // 节点code -> 所有祖先code
        childrenMap: new Map() // 父节点code -> 所有后代叶子code
    });

    // 转换树形结构（供Tree组件使用）
    const convertTreeData = (data) => {
        return data.map(item => {
            const isLeaf = !item.childrenPermissions || item.childrenPermissions.length === 0;
            return {
                key: item.permissionCode,
                title: item.permissionName,
                children: item.childrenPermissions && item.childrenPermissions.length > 0
                    ? convertTreeData(item.childrenPermissions)
                    : [],
                isLeaf: isLeaf
            };
        });
    };

    // 构建权限关系数据（核心调整：存储完整对象）
    const buildPermissionData = (data) => {
        const map = new Map(); // code -> 完整权限对象
        const leafPermissions = []; // 存储完整叶子节点对象
        const allAncestorsMap = new Map(); // 节点code -> 所有祖先code
        const childrenMap = new Map(); // 父节点code -> 所有后代叶子code

        const traverse = (items, parentKey, ancestors = []) => {
            items.forEach(item => {
                // 记录所有祖先（用code）
                allAncestorsMap.set(item.permissionCode, [...ancestors]);
                const newAncestors = [...ancestors, item.permissionCode];

                // 叶子节点处理（存储完整对象）
                if (!item.childrenPermissions || item.childrenPermissions.length === 0) {
                    map.set(item.permissionCode, item); // 存储完整对象
                    leafPermissions.push(item); // 叶子数组存完整对象
                    // 所有祖先记录这个叶子的code（用于关联）
                    newAncestors.forEach(ancestorKey => {
                        if (!childrenMap.has(ancestorKey)) {
                            childrenMap.set(ancestorKey, new Set());
                        }
                        childrenMap.get(ancestorKey).add(item.permissionCode);
                    });
                } else {
                    traverse(item.childrenPermissions, item.permissionCode, newAncestors);
                }
            });
        };

        traverse(data, null, []);

        // 转换Set为数组
        const normalizedChildrenMap = new Map();
        childrenMap.forEach((value, key) => {
            normalizedChildrenMap.set(key, Array.from(value));
        });

        return {
            map,
            count: leafPermissions.length,
            leafPermissions,
            allAncestorsMap,
            childrenMap: normalizedChildrenMap
        };
    };

    // 已选权限列表（右侧展示，从完整对象中提取信息）
    const selectedPermissionNames = useMemo(() => {
        return selectedPermissions.map(item => ({
            code: item.permissionCode,
            name: item.permissionName
        }));
    }, [selectedPermissions]);

    // 左侧树勾选事件处理（收集完整对象）
    const handleCheck = (checkedKeys) => {
        setSelectedKeys(checkedKeys);

        // 计算右侧应显示的叶子节点（完整对象）
        const leafSet = new Set();

        // 直接选中的叶子节点（通过code取完整对象）
        checkedKeys.forEach(key => {
            // 判断是否为叶子节点（通过code匹配所有叶子对象的code）
            const isLeaf = allLeafPermissions.some(leaf => leaf.permissionCode === key);
            if (isLeaf) {
                const leafObj = permissionMap.get(key); // 从map取完整对象
                leafSet.add(leafObj);
            }
        });

        // 父级选中的后代叶子节点（通过code取完整对象）
        checkedKeys.forEach(key => {
            const childrenCodes = nodeRelations.childrenMap.get(key) || []; // 后代code数组
            childrenCodes.forEach(code => {
                const leafObj = permissionMap.get(code); // 取完整对象
                leafSet.add(leafObj);
            });
        });

        // 存储完整对象数组
        setSelectedPermissions(Array.from(leafSet));
    };

    const confirmSelection = () => {
        // 传递完整权限对象数组给外部
        setPermissions(selectedPermissions);
        setVisible(false);
    };

    const queryPermissionTree = () => {
        RequestUtils.post(RequestApis.permissionManage.list, {})
            .then(res => {
                setPermissionTree(res.data.data);
            })
            .catch(err => messageApi.error(err.message));
    };

    // 权限树数据初始化（适配完整对象）
    useEffect(() => {
        if (permissionTree.childrenPermissions) {
            const {
                map,
                count,
                leafPermissions,
                allAncestorsMap,
                childrenMap
            } = buildPermissionData(permissionTree.childrenPermissions);

            setPermissionMap(map);
            setTotalPermissionCount(count);
            setAllLeafPermissions(leafPermissions); // 完整叶子对象数组
            setNodeRelations({ allAncestorsMap, childrenMap });

            // 初始化选中状态（兼容外部传入code数组或对象数组）
            if (permissions && permissions.length) {
                // 统一将外部传入的permissions转换为code数组
                const permissionCodes = permissions.map(item =>
                    typeof item === 'string' ? item : item.permissionCode
                );

                // 过滤出外部传入code对应的完整对象
                const validLeafs = leafPermissions.filter(leaf =>
                    permissionCodes.includes(leaf.permissionCode)
                );
                setSelectedPermissions(validLeafs);

                // 计算初始选中的节点code
                const initialSelectedKeys = new Set();
                validLeafs.forEach(leafObj => {
                    initialSelectedKeys.add(leafObj.permissionCode); // 只添加叶子节点本身
                });

                setSelectedKeys(Array.from(initialSelectedKeys));
            }
        }
        // eslint-disable-next-line
    }, [permissionTree, permissions]);

    // 弹窗显示/隐藏逻辑
    useEffect(() => {
        if (visible) {
            queryPermissionTree();
        } else {
            setSelectedKeys([]);
            setSelectedPermissions([]);
            setPermissionMap(new Map());
            setPermissionTree({});
            setTotalPermissionCount(0);
            setAllLeafPermissions([]);
            setNodeRelations({
                allAncestorsMap: new Map(),
                childrenMap: new Map()
            });
        }
        // eslint-disable-next-line
    }, [visible]);

    // 树形数据（供Tree组件使用）
    const treeData = useMemo(() => {
        return permissionTree.childrenPermissions
            ? convertTreeData(permissionTree.childrenPermissions)
            : [];
        // eslint-disable-next-line
    }, [permissionTree]);

    // 标签颜色
    const tagColors = [
        'rgba(24, 144, 255, 0.15)',
        'rgba(82, 196, 26, 0.15)',
        'rgba(255, 145, 0, 0.15)',
        'rgba(122, 116, 255, 0.15)',
        'rgba(255, 77, 79, 0.15)'
    ];

    return (
        <Modal
            open={visible}
            title="系统权限选择"
            width={1200}
            onCancel={() => setVisible(false)}
            footer={
                <div className="permission-modal-footer">
                    <Button type="primary" onClick={confirmSelection}>
                        确认
                    </Button>
                    <Button danger onClick={() => setVisible(false)}>
                        取消
                    </Button>
                </div>
            }
            className="permission-modal"
            destroyOnClose
        >
            {setContextHolder}
            <div className="permission-layout-container">
                {/* 左侧：权限选择区 */}
                <div className="permission-selection-panel">
                    <div className="panel-header">
                        <span className="panel-title">可选权限</span>
                        <Badge count={totalPermissionCount} className="total-count" />
                    </div>
                    <div className="permission-tree-container">
                        <Tree
                            checkable
                            defaultExpandAll
                            checkedKeys={selectedKeys}
                            onCheck={handleCheck}
                            treeData={treeData}
                            className="custom-permission-tree"
                            showIcon={false}
                        />
                    </div>
                </div>

                {/* 分隔线 */}
                <Divider type="vertical" className="layout-divider" />

                {/* 右侧：已选权限区 */}
                <div className="permission-selected-panel">
                    <div className="panel-header">
                        <span className="panel-title">已选权限</span>
                        <Badge
                            count={selectedPermissionNames.length}
                            showZero
                            className="selected-count"
                        />
                    </div>
                    <div className="selected-tags-container">
                        {selectedPermissionNames.length > 0 ? (
                            <div className="tags-grid">
                                {selectedPermissionNames.map((item, index) => (
                                    <Tag
                                        key={item.code}
                                        className="selected-tag"
                                        style={{
                                            backgroundColor: tagColors[index % tagColors.length],
                                            border: 'none',
                                            color: '#333',
                                            cursor: 'pointer'
                                        }}
                                    >
                                        {item.name}
                                    </Tag>
                                ))}
                            </div>
                        ) : (
                            <div className="no-selected-placeholder">
                                <p>暂无选中权限</p>
                                <p className="placeholder-hint">在左侧勾选权限添加到此处</p>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </Modal>
    );
};

export default PermissionSelect;